package com.ltv.xiangqibook.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.octo.captcha.service.CaptchaServiceException;

public class XiangQiPostServlet extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(XiangQiPostServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String senderName = req.getParameter("sender_name");
        String comment = req.getParameter("comment");
        String captcha = req.getParameter("input_captcha");
        String gameId = req.getParameter("game_id");
        
        String sessId = req.getSession().getId();
        
        boolean passedCaptchaTest = validateCaptcha(sessId, captcha);
        
        if (!passedCaptchaTest) {
            resp.sendRedirect("XiangQiGame?game_id=" + gameId + "&sender_name=" + senderName + "&comment=" + newLineToBreak(comment));
            return;
        }
        
        // connecting to database
        Connection con = null;  
        PreparedStatement insertPosts = null;
        String insertQuery = "insert into posts(game_id, sender_name, comment, game_url) values (?, ?, ?, ?)";
        ResultSet rs = null;
        
        try {
            con = ConnectionPool.getInstance().getConnection();
            con.setAutoCommit(false);
            
            insertPosts = con.prepareStatement(insertQuery);
            
            rs = con.createStatement().executeQuery("SELECT * FROM games where game_id='" + gameId + "'");
            if (!rs.next()) {
                resp.sendRedirect("XiangQiGame?game_id=" + gameId);
                return;
            } else {
                insertPosts.setString(4, rs.getString(4));
            }
            
            insertPosts.setString(1, gameId);
            insertPosts.setString(2, senderName);
            insertPosts.setString(3, comment);
            
            insertPosts.executeUpdate();
            con.commit();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                con.rollback();
            } catch (SQLException e1) {
                logger.error(e.getMessage(), e);
            }
        } finally {
            try {
                if(insertPosts != null) {
                    insertPosts.close();
                    insertPosts = null;
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                if(rs != null) {
                    rs.close();
                    rs = null;
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                if(con != null) {
                    ConnectionPool.getInstance().returnConnection(con);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        resp.sendRedirect("XiangQiGame?game_id=" + gameId);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
    
    private boolean validateCaptcha( String captchaId, String inputChars ) {
        boolean bValidated = false;
        try {
          bValidated = XiangQiBookCaptchaService.getInstance().validateResponseForID( captchaId, inputChars );
        } catch( CaptchaServiceException cse ){
            bValidated = false;
        }
        return bValidated;
      }
    
    private String newLineToBreak(String str) {
        String ret = "";
        String arr[] = str.split("\n");
        for (int i = 0; i < arr.length - 1; i++) {
            ret += arr[i] + "<br>";
        }
        ret += arr[arr.length - 1];
        return ret;
    }

}
